/*! \file button.cpp	
	
	This contains the implementation of the Button class
*/

#include "button.h"
#include "guiclass.h"
#include "image.h"
#include <GL\glfw.h>

	
Button::Button( Component* parent, string label ) :
	Component( parent ),
	label(label)
	{
		widthOfText = GUI::getInstance()->getFont()->widthOfString( label );
		//~ cout << "WIDTH OF BUTTON TEXT" << widthOfText << endl;
		setWidth( widthOfText + BUTTON_LABEL_PADDING_X * 2 );
		depressed = false;
		addListener( this );
	}

void Button::draw() {
	
	Color topColor = bgColorTop;
	Color bottomColor = bgColorBottom;
	
	int sideID = sideID1;
	int cornerID = cornerID1;
	
	if ( mouseIsOver ) {
		topColor = bgColorBottom;
		bottomColor = bgColorTop;
	}
	
	if ( mouseIsDown || depressed ) {
		topColor = Color( .842f, .842f, .842f );
		bottomColor = Color( .842f, .842f, .842f );
		sideID = sideID2;
		cornerID = cornerID2;
	}
	int screenX = getScreenX(), screenY = getScreenY();
	
	GUI::getInstance()->drawRectangle( screenX, screenY, w, h, topColor, bottomColor );
	
	glColor4f( 0.0f, 0.0f, 0.0f, 1.0f );
	//~ glEnable(GL_TEXTURE_2D);
	Font* font = GUI::getInstance()->getFont();
	font->writeString( label, BUTTON_LABEL_PADDING_X, h - font->getMaxAdvanceY() / 2 );	
	if ( border ) {
		ImageHandler::getInstance()->guiBorder( sideID, cornerID, screenX, screenY, w, h );
	}
}

void Button::update() {
}


void Button::performAction() {
	cout << "Action performed" << endl;
	vector<Listener*>::iterator j;
	for ( j = listeners.begin(); j != listeners.end(); ++j ) {
		(*j)->actionPerformed( Event( this ) );
	}
}

void Button::keyDown( Event e ) {
	cout << "Key was pressed on this. " << e.button << endl;
	if ( e.button == GLFW_KEY_ENTER ) {
		// this would immediately run whatever function there is, not wait for release
		performAction();
	}
	if ( e.button == GLFW_KEY_SPACE ) {
		((Button*)(e.spawningComponent))->setDepressed();
	}
}

void Button::mouseUp( Event e ) {
	if ( mouseIsOver ) {
		performAction();
	}
}

void Button::keyUp( Event e ) {
	cout << "Key was released on this. " << e.button << endl;
	if ( e.button == GLFW_KEY_SPACE && ((Button*)(e.spawningComponent))->isDepressed() ) {
		((Button*)(e.spawningComponent))->setDepressed( false );
	}
}
